<?php
/**
 * ExtBasicFormController class file
 *
 * @author TrueSoftware B.V. (The Netherlands)
 * @link http://www.ext4yii.com
 * @copyright Copyright 2007-2010 TrueSoftwareB.V. all rights reserved.
 * @license http://www.ext4yii.com/license/
 *          EVALUATION VERSION - NOT FOR COMMERCIAL USE OR DISTRIBUTION.
 * @version 0.7.2
 */
 
 
abstract class ExtBasicFormController extends ExtController
{
    protected abstract function Save($data);
    protected abstract function Load();

    public function registerAjaxMethods()
    {
        $this->registerAjaxMethod('form_submit');
        $this->registerAjaxMethod('form_load');
    }

    protected function fatalError($message)
    {
        header('HTTP/1.1 500 EXT4YII_FORM_ERROR');
        echo $message;
    }

    public function action_submit()
    {
        $result = $this->Save($_POST);
        if(is_bool($result))
        {
            $jso = new ExtJavaScriptObject();
            $jso->addBoolean('success', $result);
            echo $jso->render();
        }
        else if(is_array($result))
        {
            echo CJSON::encode($result);
        }
        else
        {
            $this->fatalError('<b>Save Operation Failed.</b> The Save operation should either return a boolean value or an array containing operation results. Please see documentation.');
        }
    }

    public function action_load()
    {
        $data = $this->Load();
        if(is_bool($data) && $data === false)
        {
            $jso = new ExtJavaScriptObject();
            $jso->addBoolean('success', false);
            echo $jso->render();
        }
        else if(is_array($data))
        {
            echo CJSON::encode($data);
        }
        else
        {
            $this->fatalError('<b>Load Operation Failed.</b> The Load operation should either return a FALSE or an array containing operation results. Please see documentation.');
        }
    }

    protected function returnLoadResult($data,$success='true',$errorMessage='')
    {
        if(!$success && is_null($data))
            $data = array();
        return array('success'=>$success,'errorMessage'=>$errorMessage,'data'=>$data);
    }
}
?>
